//index.js
//获取应用实例
const app = getApp()
var core = require("../../utils/core.js");
import Toast from '../../components/dist/toast/toast';
Page({
  data: {
    imgUrls: [
      'https://shop-sqpt.eshezhong.com/attachment/upload/3/picture/2019-01-08/5c34103ff11d7.jpg',
      'https://shop-sqpt.eshezhong.com/attachment/upload/3/picture/2019-01-23/5c47d7e00347f.jpg',
      'https://shop-sqpt.eshezhong.com/attachment/upload/3/picture/2019-01-23/5c47d7e00347f.jpg'
    ],
    indicatorDots: false,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    pageState: 1, //0 出现往期团购  1出现正在团购
    pageNavState: 0, //导航状态   0 正在抢购   1即将开始
    cutStartTime: 1548743368000, //倒计时结束时间
    cutTimer: '', //
    cutTime_h: '00', //时
    cutTime_m: '00', //分
    cutTime_s: '00', //秒
    scrollTop: 0,
    winHeight: "", //窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    expertList: [{ //假数据
      img: "avatar.png",
      name: "欢顔",
      tag: "知名情感博主",
      answer: 134,
      listen: 2234
    }],
    nowListId: '', //正在抢购的id
    afterListId: '', //即将抢购的id
    currentpageNum: 1, //记录当前数据页数（第几页）默认第一页
    currentTypeName: '全部商品', //当前请求的分类
    loadingShow: false,
    dataInfoList: [], //获取的数据数组
    hasMoreData: false, //是否有更多数据
    haveNoData: false, //没有数据提示
    shequData: '', //社区的信息
    userTimer: '', //获取用户信息的定时器
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onShow: function() {
    console.log('index  OnShow');
    var that = this;
    setTimeout(function() {
      if (that.checkLogin()) { //已经登陆
        console.log(38)
        that.setData({
          loadingShow: true
        })
        wx.getStorage({
          key: 'choosedSheQu',
          success: function(res) {
            console.log(res)
            that.setData({
              shequData: res.data,
              currentpageNum:1
            })

            that.getDataInfo();
          },
          fail:function(){
            wx.navigateTo({
              url: '/pages/location/location',
            })
          }
        })

       
      } else { //需要登陆
        app.getUserInfo();
      }
    }, 500);
   
  },

  getDataInfo: function() { //获取数据
    var that = this;
    core.get("groupapp/index/group_list", {}, function(t) {


    })
    core.get("groupapp/index/group_goods", {}, function(t) {

      that.setData({
        loadingShow: false
      })
      if (t.status == 1) {
        if (t.result.now_list) { //正在抢购 有值
          //设置倒计时时间
          that.data.cutStartTime = t.result.now_list.endtime * 1000;
          that.setData({ //先保存正在抢购对应的id
            nowListId: t.result.now_list.id
          })
          that.getNowListInfo(t.result.now_list.id, '全部商品', 1); //获取正在抢购的数据
        } else { //没有正在抢购的数据
          that.setData({
            nowListId: ''
          })
        }
        if (t.result.after_list) { //即将抢购 有值
          that.setData({ //先保存正在抢购对应的id
            afterListId: t.result.after_list.id
          })

        } else {
          that.setData({ //没有即将抢购的数据
            afterListId: ''
          })
        }
        that.cutTime(); //开启倒计时

      } else {
        //获取数据失败
        Toast('数据获取失败');
      }
    })
  },
  getNowListInfo: function(id, type, page) { //获取正在抢购的数据
  console.log(page);
    var type = type;

    if (type == '全部商品') {

      type = ''
    }
    var that = this;
    that.setData({
      loadingShow: true
    })
    core.get("groupapp/index/group_cat_goods", {
      pid: id, //对应接口返回id
      cname: type, // 分类名称
      page: page, // 页码
    }, function(t) {

      that.setData({
        loadingShow: false
      })

      if (that.data.currentpageNum == 1) { //第一页数据
        console.log('1页数据')
        if (t.result.list.length) {
          that.setData({
            dataInfoList: that.ProcessingData(t.result.list),
            hasMoreData: true,
            haveNoData: false
          })
        } else {

          that.setData({
            dataInfoList: [],
            hasMoreData: false,
            haveNoData: true
          })
        }
      } else { //大于1页数据
        console.log('大于1页数据')
        var arr = that.data.dataInfoList;
        if (t.result.list.length) {

          arr.push(that.ProcessingData(t.result.list))
          that.setData({
            dataInfoList: arr,
            hasMoreData: true,
            haveNoData: false
          })
        } else {

          that.setData({
            dataInfoList: arr,
            hasMoreData: false,
            haveNoData: true
          })
        }
      }

    })
  },
  getAfterList: function(id, type, page) {
    var type = type;
    if (type == '全部商品') {

      type = ''
    }
    var that = this;
    that.setData({
      loadingShow: true
    })
    core.get("groupapp/index/group_cat_goods", {
      pid: id, //对应接口返回id
      cname: type, // 分类名称
      page: page, // 页码
    }, function(t) {
      that.setData({
        loadingShow: false
      })
      if (that.data.currentpageNum == 1) {
        if (t.result.list.length) {
          that.setData({
            dataInfoList: that.ProcessingData(t.result.list),
            hasMoreData: true,
            haveNoData: false
          })
        } else {
          that.setData({
            dataInfoList: [],
            hasMoreData: false,
            haveNoData: true
          })
        }
      } else {
        var arr = that.data.dataInfoList;
        if (t.result.list.length) {
          arr.push(that.ProcessingData(t.result.list))
          that.setData({
            dataInfoList: arr,
            hasMoreData: true,
            haveNoData: false
          })
        } else {
          that.setData({
            dataInfoList: arr,
            hasMoreData: false,
            haveNoData: false
          })
        }

      }




    })
  },
  ProcessingData: function(arr) { //处理数据
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
      arr[i].price_start = arr[i].groupprice.split('.')[0];
      arr[i].price_end = arr[i].groupprice.split('.')[1];
      newArr.push(arr[i])
    }
    return newArr;
  },
  cutTime: function() { //倒计时方法
    var that = this;
    if (this.data.cutStartTime > new Date().getTime()) {
      that.data.cutTimer = setInterval(function() {
        that.formatDuring(that.data.cutStartTime - new Date().getTime());
      }, 1000)
    } else { //倒计时完成
      clearInterval(that.data.cutTimer);
      that.setData({
        cutTime_h: '00', //时
        cutTime_m: '00', //分
        cutTime_s: '00', //秒
      })
    }
  },
  formatDuring: function(mss) {
    var that = this;
    var days = parseInt(mss / (1000 * 60 * 60 * 24));
    var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = parseInt((mss % (1000 * 60)) / 1000);
    that.setData({
      cutTime_h: hours + days * 24, //时
      cutTime_m: minutes, //分
      cutTime_s: seconds, //秒
    })
    return days + "天" + hours + "小时 " + minutes + "分钟 " + seconds + "秒 ";
  },
  checkLogin: function() {
    console.log(app.getCache("userinfo"));
    setTimeout(function(){
      console.log(app.getCache("userinfo"));
    },1000)
    if ("" == app.getCache("userinfo")) {

      return false
    } else {

      return true;
    }

  },
  onLoad: function() {
    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        that.setData({
          winHeight: calc
        });
      }
    });



  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  changeNav: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    this.setData({
      pageNavState: index,
      currentpageNum: 1, //切换分类  页数重新变为1
      currentTypeName: '全部商品', //切换分类  分类名称变为 全部商品
      currentTab: 0,
      dataInfoList: [], //切换一级分类，先清空数组
    })
    //切换请求会议分类 下的全部商品的第一页数据
    if (index == 1) {
      //获取即将抢购的数据
      that.getAfterList(that.data.afterListId, '全部商品', 1);
    } else if (index == 0) {
      that.getNowListInfo(that.data.nowListId, '全部商品', 1); //获取正在抢购的数据
    }
  },
  onPageScroll(event) {
    this.setData({
      scrollTop: event.scrollTop
    });
  },
  // 滚动切换标签样式
  switchTab: function(e) {
    this.setData({
      currentTab: e.detail.current
    });
    this.checkCor();
  },
  // 点击标题切换当前页时改变样式
  swichNav: function(e) {
    var that = this;
    var cur = e.target.dataset.current;
    var name = e.target.dataset.name;
    if (this.data.currentTaB == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur,
        currentpageNum: 1, //切换二级分类  页数重新变为1
        currentTypeName: name, //切换二级分类  分类名称动态改变
      })
      // 请求对应的currentTab页面下的数据    0 正在抢购   1即将开始
      if (that.data.pageNavState == 0) { //正在抢购
        that.getNowListInfo(that.data.nowListId, name, 1);
      } else if (that.data.pageNavState == 1) { //即将开始
        that.getAfterList(that.data.afterListId, name, 1);
      }
    }
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function() {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  goodDetail: function(e) {
    var goodId = e.currentTarget.dataset.goodid;
    console.log(goodId);
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodid=' + goodId,
    })

  },
  getLocation: function() {
    wx.navigateTo({
      url: '/pages/location/location',
    })

  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading() //在标题栏中显示加载

    this.onShow();
    setTimeout(function() {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1000)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    // 请求对应的currentTab页面下的数据    0 正在抢购   1即将开始
    var currentpageNum = that.data.currentpageNum;
    that.setData({
      currentpageNum: currentpageNum + 1
    })
    if (that.data.pageNavState == 0) { //正在抢购

      that.getNowListInfo(that.data.nowListId, that.data.currentTypeName, that.data.currentpageNum);

    } else if (that.data.pageNavState == 1) { //即将开始

      that.getAfterList(that.data.afterListId, that.data.currentTypeName, that.data.currentpageNum);

    }




  },

})